import { LOGIN_TOKEN } from '@/global/constants'
import Storage from '@/utils/Storeage'
import { createRouter, createWebHashHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'

const routes: readonly RouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/main',
  },
  {
    path: '/login',
    component: () => import("@/views/Login/index.vue")
  },
  {
    path: '/main',
    component: () => import("@/views/Home/index.vue")
  },
  {
    path: '/:pathMatch(.*)*',
    name: '404',
    component: () => import("@/views/NotFount.vue")
  }
]

const router = createRouter({
  routes: routes,
  history: createWebHashHistory()
})


// 路由的导航守卫：
// beforeEach 前置路由守卫 在跳转之前
router.beforeEach((to) => {
  const token = Storage.get(LOGIN_TOKEN)
  if (to.path === '/main' && !token) {
    return { path: '/login' }
  } else if (token && to.path === '/login') {
    return false
  }
})

export default router
